//
//  GroupShopingViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/25.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "GroupShopingViewController.h"
#import "GroupShopingTableViewCell.h"
#import "GroupShoppingDetailViewController.h"
#import "WebDetailInfoViewController.h"
#import "QuestionTypeTableViewCell.h"
static NSString * typeCellIndentfier = @"QuestionTypeTableViewCell";
static NSString * cellIndentfier = @"GroupShopingTableViewCell";
@interface GroupShopingViewController ()<DYQBannerScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong,nonatomic) DYQBannerScrollView *bannerScrollView;//广告栏
@property (nonatomic,strong)  NSMutableArray  *bannerArray;
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *navSearchBackView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIView *typeView;
@property (strong, nonatomic) IBOutlet UIButton *maskView;
@property (strong, nonatomic) IBOutlet UITextField *searchField;
@property (strong, nonatomic) IBOutlet UITableView *typeTableView;//筛选tableView
@property (strong, nonatomic) IBOutlet UITableView *listTableView;//商品展示tableView
@property (strong, nonatomic) IBOutlet UIButton *typeButton;//分类
@property (strong, nonatomic) IBOutlet UIButton *typeSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *pickSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *pickButton;//筛选
@property (strong, nonatomic) IBOutlet UIButton *rankButton;//智能排序
@property (strong, nonatomic) IBOutlet UIButton *rankSmallButton;

@property(strong,nonatomic)NSMutableArray * typesArray;
@property(strong,nonatomic)NSMutableArray * rankArray;
@property(strong,nonatomic)NSMutableArray * pickArray;
@property(strong,nonatomic)NSMutableDictionary * choseTypeDic;
@property(strong,nonatomic)UIButton * currentButton;


@property(nonatomic,strong)NSMutableArray * groupShoppings;
@property(nonatomic,strong)NSMutableArray * openSections;
@end

@implementation GroupShopingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;

    _choseTypeDic = [NSMutableDictionary dictionary];
    _openSections = [NSMutableArray array];
    _typesArray = [NSMutableArray array];
    _rankArray = [NSMutableArray array];
    _pickArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    _groupShoppings = [NSMutableArray array];
    _bannerArray = [NSMutableArray array];
    [self initViewLayout];
    [self getAdvertiseBanner];
    [self addRefreshing];
    [self getTypes];
    // Do any additional setup after loading the view.
}


- (void)initViewLayout{

    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.typeView];
    _navSearchBackView.layer.borderWidth = 1;
    _navSearchBackView.layer.borderColor = [UIColor colorWithWhite:0.882 alpha:1.000].CGColor;
    _navSearchBackView.layer.cornerRadius = 15*VerticalRatio();
    
    
    //广告栏
    self.bannerScrollView = [[DYQBannerScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 113), NO)];
    self.bannerScrollView.backgroundColor = [UIColor clearColor];
    self.bannerScrollView.pageControlPosition = PageControlPositionCenter;
    self.bannerScrollView.noDataPlaceholderImage = [UIImage imageNamed:@"cover_cy"];
    self.bannerScrollView.timeInterval = 3;
    self.bannerScrollView.pageControllerTintColor = [UIColor whiteColor];
    self.bannerScrollView.pageControllerCurrentColor = [UIColor orangeColor];
    
    [self.scroView addSubview:_bannerScrollView];
    self.scroView.contentSize = flexibleSize(CGSizeMake(0, 504+180), YES);
    _scroView.delegate = self;
    
     [self.listTableView registerNib:[UINib nibWithNibName:cellIndentfier bundle:nil] forCellReuseIdentifier:cellIndentfier];
    
    [self.typeTableView registerNib:[UINib nibWithNibName:typeCellIndentfier bundle:nil] forCellReuseIdentifier:typeCellIndentfier];
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark === 筛选类型
- (IBAction)choseType:(UIButton * )sender {
    
    _typeTableView.dataSource = self;
    _typeTableView.delegate = self;
    
    UIButton * button = [[UIButton alloc]init];
    if (sender == _typeButton) {
        button = _typeSmallButton;
    }else if(sender == _pickButton){
        button = _pickSmallButton;
    }else{
        button = _rankSmallButton;
    }
    
    if (button != _currentButton) {
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        _currentButton = button;
    }
   
    NSInteger lines = 0;
    if (sender == _typeButton) {
        _typeButton.selected = YES;
        _typeSmallButton.selected = YES;
        _rankButton.selected = NO;
        _rankSmallButton.selected = NO;
        _pickButton.selected = NO;
        _pickSmallButton.selected = NO;
        [_typeSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        lines = _typesArray.count;
    }else if (sender == _rankButton){
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _rankButton.selected = YES;
        _rankSmallButton.selected = YES;
        _pickButton.selected = NO;
        _pickSmallButton.selected = NO;
        [_rankSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];

        _rankArray =[@[@"智能排序",@"评价最高",@"销量最高"]mutableCopy];
        lines = _rankArray.count;
    }else{
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _rankButton.selected = NO;
        _rankSmallButton.selected = NO;
        _pickButton.selected = YES;
        _pickSmallButton.selected = YES;
        [_pickSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];

        _pickArray =[@[@"免预约",@"节假日可用"]mutableCopy];
        lines = _pickArray.count;
    }
    
    if (lines>4) {
        lines = 4;
    }
    [UIView animateWithDuration:0.5 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(0, 223, 320, 45*lines), YES);
         _maskView.alpha = 1;
    }completion:^(BOOL finished) {
        _maskView.hidden = NO;
    }];
    [_typeTableView reloadData];


}
- (IBAction)closeTypeView:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{ _typeTableView.frame = flexibleFrame(CGRectMake(0, 223, 320, 0), YES);
        _maskView.alpha = 0;
       }completion:^(BOOL finished) {
        _maskView.hidden = YES;
       }];
    [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
}

#pragma mark == 美食
- (IBAction)foods:(id)sender {
}
#pragma mark == 娱乐
- (IBAction)happy:(id)sender {
}
#pragma mark == 购物
- (IBAction)shopping:(id)sender {
}
#pragma mark == 生活服务
- (IBAction)Service:(id)sender {
}
#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryMallADDData" forKey:@"method"];
    [dic setObject:@"1" forKey:@"position"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_ADBanner withHttpType:@"POST" withTag:SX_kADBannerTag];
}


- (void)getTypes{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryMallGrouponCategory withHttpType:@"POST" withTag:SX_SX_queryMallGrouponCategory];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getGroupShoppings];
        });
    }];
    // 马上进入刷新状态
    [self.scroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.groupShoppings.count == _totle) {
        [self.listTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getGroupShoppings];
        });
    }
    
}

- (void)getGroupShoppings{
    [_openSections removeAllObjects];
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_searchField.text.length>0) {
        [dic setObject:_searchField.text forKey:@"goodsType"];
    }else{
        [dic setObject:@"" forKey:@"goodsType"];
    }
    
    
    NSIndexPath * path = _choseTypeDic[@"type"];
    if (path) {
         [dic setObject:_typesArray[path.row][@"mgcaId"] forKey:@"goodsName"];
    }else{
        [dic setObject:@"" forKey:@"goodsName"];
    }
   
    
    NSIndexPath * pathsold = _choseTypeDic[@"rank"];
    if (pathsold) {
        [dic setObject:@(pathsold.row) forKey:@"isSold"];
    }else{
    [dic setObject:@0 forKey:@"isSold"];
    }
    

    NSIndexPath * pathfree = _choseTypeDic[@"pick"];
    if (pathfree) {
        if (pathfree.row==0) {
            [dic setObject:@"1" forKey:@"isFree"];
            [dic setObject:@"" forKey:@"IsHoliday"];
        }else if(pathfree.row==1 ){
            [dic setObject:@"" forKey:@"isFree"];
            [dic setObject:@"1" forKey:@"IsHoliday"];
        }
    }else{
     [dic setObject:@"" forKey:@"isFree"];
    [dic setObject:@"" forKey:@"IsHoliday"];
    }
    
    
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppBuyHome withHttpType:@"POST" withTag:SX_SX_queryAppBuyHome];
    
}

#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}


- (void)footerHandel:(UIButton *)sender{
    [_openSections addObject:@(sender.tag/200-1)];
    [_listTableView reloadData];
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView == _listTableView) {
        if ([_openSections containsObject:@(section)]) {
            return 0;
        }else{
         NSArray * arrey = _groupShoppings[section][@"list"];
        if (arrey.count>2) {
            return 38*VerticalRatio();
        }else{
            return 0;
        }
       }
    }else{
        return 0;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == _listTableView) {
        return 60*VerticalRatio();
    }else{
        return 0;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NSDictionary * dic = _groupShoppings[section];
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 60), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * storeName = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(10, 10, 300, 15), YES)];
    storeName.textColor = [UIColor colorWithWhite:0.075 alpha:1.000];
    storeName.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
    storeName.text = [NSString stringWithFormat:@"%@",dic[@"storeName"]];
    [view addSubview:storeName];
    
    CommitStarsView * starsView = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(10, 36, 70, 13), NO) SmallStars:[dic[@"mgpicomm"] floatValue]/2];
    [view addSubview:starsView];
    
    
    UILabel * score = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(70, 35, 100, 13), NO)];
    score.textColor = [UIColor colorWithRed:0.984 green:0.733 blue:0.255 alpha:1.000];
    score.font = [UIFont systemFontOfSize:12*VerticalTexeRatio()];
    score.text = [NSString stringWithFormat:@"%.1f分",[dic[@"mgpicomm"] floatValue]/2];
    [view addSubview:score];
    
    UIImageView * image = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(237, 36, 12, 15), NO)];
    image.image = [UIImage imageNamed:@"map"];
    [view addSubview:image];
    
    UILabel * address = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(255, 37, 65, 13), NO)];
    address.textColor = [UIColor colorWithWhite:0.565 alpha:1.000];
    address.font = [UIFont systemFontOfSize:12*VerticalTexeRatio()];
    address.text = [NSString stringWithFormat:@"%@",dic[@"addressName"]];
    [view addSubview:address];
    //计算字符串长度
    NSString *str = dic[@"addressName"];
    CGSize size = CGSizeMake(kDeviceWidth, 13*VerticalRatio());
    CGSize sizeLabel = [str sizeWithFont:[UIFont systemFontOfSize:12*VerticalTexeRatio()] maxSize:size];
    
    address.frame = CGRectMake(kDeviceWidth-sizeLabel.width-5, 37*VerticalRatio(), sizeLabel.width, 13*VerticalRatio());
    image.frame = CGRectMake(kDeviceWidth-sizeLabel.width-15-5, 36*VerticalRatio(), 12*VerticalRatio(), 15*VerticalRatio());
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 59, 320, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [view addSubview:line];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 38), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 33, 320, 5), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.945 alpha:1.000];
    [view addSubview:line];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(0, 0, 320, 33), YES);
    button.tag = 200*(section+1)+1;
    [button setTitle:@"其他团购" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithWhite:0.459 alpha:1.000] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(footerHandel:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:14*VerticalTexeRatio()];
    [view addSubview:button];
    
    UIImageView * image = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(85, 15, 9, 5), NO)];
    image.image = [UIImage imageNamed:@"groupShoping5"];
    [view addSubview:image];
    return view;
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView != _typeTableView) {
        return _groupShoppings.count;
    }else{
    return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _listTableView) {
        return 66*VerticalRatio();
        
    }else{
        return 45*VerticalRatio();
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _typeTableView) {
        if (_typeButton.selected) {
            return _typesArray.count;
        }else if (_rankButton.selected){
            return _rankArray.count;
        }else if(_pickButton.selected){
            return _pickArray.count;
        }
        
    }else{
       
        NSArray * arrey = _groupShoppings[section][@"list"];
        if ([_openSections containsObject:@(section)]) {
            return arrey.count;
        }else{
            NSInteger number = arrey.count;
            if (arrey.count>2) {
                number = 2;
            }
            return number;
        }
       
    }
    return 0;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != _listTableView) {
        QuestionTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:typeCellIndentfier];
        if (cell == nil) {
            cell= [[QuestionTypeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:typeCellIndentfier];
            
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        
        cell.typeName.textColor = [UIColor colorWithWhite:0.243 alpha:1.000];
        cell.typeButton.selected = NO;
        NSIndexPath * path = [[NSIndexPath alloc]init];
        if (_rankButton.selected==YES) {
            cell.typeName.text = [NSString stringWithFormat:@"%@",_rankArray[indexPath.row]];
            path = _choseTypeDic[@"rank"];
        }else if (_typeButton.selected==YES) {
            cell.typeName.text = [NSString stringWithFormat:@"%@",_typesArray[indexPath.row][@"mgcaName"]];
             path = _choseTypeDic[@"type"];
        }else if (_pickButton.selected==YES){
            cell.typeName.text = [NSString stringWithFormat:@"%@",_pickArray[indexPath.row]];
             path = _choseTypeDic[@"pick"];
        }
        
        if (indexPath == path) {
            cell.typeName.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.086 alpha:1.000];
            cell.typeButton.selected = YES;
        }
        
        
        return cell;
    }else{
        GroupShopingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentfier];
        if (cell == nil) {
            cell= [[GroupShopingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentfier];
            
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        NSDictionary * dic = _groupShoppings[indexPath.section][@"list"][indexPath.row];
        
        
//        

        cell.shoppingName.text = [NSString stringWithFormat:@"%@",dic[@"mgprName"]];
        cell.shoppingPrice.text = [NSString stringWithFormat:@"¥%@",dic[@"mgpiGourponAmount"]];
        cell.shoppingOldPrice.text = [NSString stringWithFormat:@"%@",dic[@"mgpiOrginalAmount"]];
        NSUInteger length = [cell.shoppingOldPrice.text length];
        
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:cell.shoppingOldPrice.text];
        [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
        [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, length)];
        [cell.shoppingOldPrice setAttributedText:attri];
        cell.shoppingSoldNumber.text = [NSString stringWithFormat:@"已售%@",dic[@"mgpiSold"]];
        //计算字符串长度
        NSString *str = cell.shoppingSoldNumber.text;
        CGSize size = CGSizeMake(kDeviceWidth, 15*VerticalRatio());
        CGSize sizeLabel = [str sizeWithFont:[UIFont systemFontOfSize:12*VerticalTexeRatio()] maxSize:size];
        cell.shoppingSoldNumber.frame = CGRectMake(kDeviceWidth-sizeLabel.width-15-5, 37*VerticalRatio(), sizeLabel.width, 15*VerticalRatio());
        if (![dic[@"phoneImg"] isEqual:[NSNull null]]) {
            NSString *image =  dic[@"phoneImg"];
            [cell.shoppingImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            cell.shoppingImage.image = [UIImage imageNamed:@"gsInfo1"];
        }
        
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _listTableView) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        GroupShoppingDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"GroupShoppingDetail"];
        page.groupShoppingId = _groupShoppings[indexPath.section][@"list"][indexPath.row][@"mgprId"];
        [self.navigationController   pushViewController:page animated:YES];
    }else{
        NSString * key = @"";
        if (_currentButton == _typeSmallButton) {
            [_typeButton setTitle:_typesArray[indexPath.row][@"mgcaName"] forState:UIControlStateNormal];
            CGSize size = [_typeButton.titleLabel.text sizeWithFont:_typeButton.titleLabel.font];
            if (size.width>_typeButton.frame.size.width) {
                size.width = _typeButton.frame.size.width-_typeSmallButton.frame.size.width;
            }
            _typeSmallButton.frame =CGRectMake(CGRectGetMinX(_typeButton.frame)+(_typeButton.frame.size.width-size.width)/2+size.width+1, _typeSmallButton.frame.origin.y, _typeSmallButton.frame.size.width, _typeSmallButton.frame.size.height);
            
            key = @"type";
           
        }else if (_currentButton == _rankSmallButton){
         [_rankButton setTitle:_rankArray[indexPath.row] forState:UIControlStateNormal];
            CGSize size = [_rankButton.titleLabel.text sizeWithFont:_rankButton.titleLabel.font];
            if (size.width>_rankButton.frame.size.width) {
                size.width = _rankButton.frame.size.width-_rankSmallButton.frame.size.width;
            }
            _rankSmallButton.frame =CGRectMake(CGRectGetMinX(_rankButton.frame)+(_rankButton.frame.size.width-size.width)/2+size.width+1, _rankSmallButton.frame.origin.y, _rankSmallButton.frame.size.width, _rankSmallButton.frame.size.height);
             key = @"rank";
        }else{
         [_pickButton setTitle:_pickArray[indexPath.row] forState:UIControlStateNormal];
            CGSize size = [_pickButton.titleLabel.text sizeWithFont:_pickButton.titleLabel.font];
            if (size.width>_pickButton.frame.size.width) {
                size.width = _pickButton.frame.size.width-_pickSmallButton.frame.size.width;
            }
            _pickSmallButton.frame =CGRectMake(CGRectGetMinX(_pickButton.frame)+(_pickButton.frame.size.width-size.width)/2+size.width+1, _pickSmallButton.frame.origin.y, _pickSmallButton.frame.size.width, _pickSmallButton.frame.size.height);
            key = @"pick";
        }
        
        NSIndexPath * path = _choseTypeDic[key];
        QuestionTypeTableViewCell * cell = [_typeTableView cellForRowAtIndexPath:path];
        cell.typeButton.selected = NO;
        cell.typeName.textColor = [UIColor colorWithWhite:0.243 alpha:1.000];
        
        QuestionTypeTableViewCell * Cell = [_typeTableView cellForRowAtIndexPath:indexPath];
        Cell.typeButton.selected = YES;
        Cell.typeName.textColor = [UIColor colorWithRed:1.000 green:0.643 blue:0.086 alpha:1.000];
        
        [_choseTypeDic setObject:indexPath forKey:key];
        
        
        
        [UIView animateWithDuration:0.5 animations:^{ _typeTableView.frame = flexibleFrame(CGRectMake(0, 223, 320, 0), YES);
            _maskView.alpha = 0;
        }completion:^(BOOL finished) {
            _maskView.hidden = YES;
        }];
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
    }
    [self addRefreshing];

  
}

#pragma   mark---- textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.scroView.header beginRefreshing];
    return YES;
}

#pragma mark----DYQBannerScrollViewDelegate

-(void)bannerScrollView:(DYQBannerScrollView *)bannerScrollView didSelectItemAtIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    WebDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebDetailInfo"];
    page.objectId = _bannerArray[index][@"appAdertUrl"] ;
    page.titleStr = @"详情";
    page.meType = @"4";
    [self.navigationController  pushViewController:page animated:YES];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_scroView.header endRefreshing];
    [_scroView.footer endRefreshing];
  
    if (tag==SX_kADBannerTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [self.imageArray removeAllObjects];
            //            self.imageArray = database[@"result"];
            for (NSDictionary *data in database[@"result"]) {
                [_bannerArray addObject:data];
                NSString * picture = [Common stringFromData:data[@"appAdertImagUri"]];
                [self.imageArray addObject:picture];
            }
            _bannerScrollView.imageUrls = _imageArray;
            _bannerScrollView.delegate = self;
            
        }
    }else if (tag == SX_SX_queryAppBuyHome){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.listTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.listTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.groupShoppings removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.groupShoppings addObject:entity];
                }
                _listTableView.dataSource = self;
                _listTableView.delegate = self;
                [_listTableView reloadData];
                
            });
        }
    }else if (tag == SX_SX_queryMallGrouponCategory){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _typesArray = database[@"result"];
        }
    
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        
        //
        [self dismissWaitDialog];
        
        
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
